package com.net.xpay.backend.scheduler;

import com.net.xpay.common.domain.User;
import com.net.xpay.common.helper.NoticeHelper;
import com.net.xpay.common.manager.UserManager;
import com.net.xpay.core.domain.safePay.SafePayBatch;
import com.net.xpay.core.enums.SafePayBatchStatus;
import com.net.xpay.core.manager.safePay.SafePayBatchManager;
import com.net.xpay.core.model.SafePayBatchSearchModel;
import com.net.xpay.core.service.safePay.SafePayService;
import com.net.shard.ShardDataSource;
import com.net.shard.ShardDataSourceConfigurer;
import com.net.shard.ShardUtil;
import com.net.shard.domain.ShardConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class SafePayScheduler {


    @Autowired
    @Qualifier("shardDataSource")
    private DataSource shardDataSource;

    @Autowired
    private SafePayService safePayService;

    @Autowired
    private SafePayBatchManager safePayBatchManager;

    @Autowired
    private UserManager userManager;

    @Autowired
    private NoticeHelper noticeHelper;

    /**
     * 关闭超过1天未转账的批次
     */
    @Scheduled(cron = "0 0 2 * * *")
    public void closeSafePayBatch() {
        ShardDataSourceConfigurer shardDataSourceConfigurer = ((ShardDataSource) shardDataSource).getShardDataSourceConfigurer();
        Map<Long, ShardConfig> shardConfigMap = shardDataSourceConfigurer.getShardConfigMap();
        for (Long shardId : shardConfigMap.keySet()) {
            try {
                ShardUtil.setShardContext(shardId);
                doCloseSafePayBatch();
            } catch (Exception e) {
                log.warn("closeSafePayBatch error", e);
            } finally {
                ShardUtil.cleanShardContext();
            }
        }
    }


    private void doCloseSafePayBatch() {
        LocalDateTime maxCreateTime = LocalDateTime.now().minusDays(1L);
        SafePayBatchSearchModel searchModel = new SafePayBatchSearchModel();
        searchModel.setStatus(SafePayBatchStatus.WAIT_ENSURE);//处理中的
        searchModel.setMaxCreateTime(maxCreateTime);

        List<Long> batchIds = safePayBatchManager.listIds(searchModel);
        log.info("closeSafePayBatch batchIds size={}", batchIds.size());

        long t1 = System.currentTimeMillis();
        for (Long id : batchIds) {
            try {
                SafePayBatch batch = safePayBatchManager.getById(id);
                User user = userManager.getById(batch.getUserId());
                safePayService.closeSafePayBatchById(user, id);
                log.info("doCloseSafePayBatch success id={}", id);
            } catch (Exception e) {
                log.warn("closeSafePayBatchById error id={}", id, e);
                noticeHelper.sendSystemMonitorNotice("自动关闭超时安全付订单失败 系统批次号：" + id, "text");
            }
        }
        log.info("closeSafePayBatch batchIds end cost={} ms", System.currentTimeMillis() - t1);
    }
}
